package com.zh.rent.controller.backstage;

import com.github.pagehelper.PageInfo;
import com.zh.rent.pojo.Account;
import com.zh.rent.pojo.Invitation;
import com.zh.rent.pojo.Setup;
import com.zh.rent.pojo.StandbyAccount;
import com.zh.rent.service.AccountService;
import com.zh.rent.service.InvitationService;
import com.zh.rent.service.SetupService;
import com.zh.rent.service.StanAccountService;
import com.zh.rent.util.JsonResult;
import com.zh.rent.util.UuidUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.omg.CORBA.OBJECT_NOT_EXIST;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/bacaccount")
@Api(tags="账号后台管理")
public class BacAccountController {
    @Autowired
    AccountService AccountServiceImpl;
    @Autowired
    InvitationService InvitationServiceImpl;
    @Autowired
    StanAccountService StanAccountServiceImpl;
    @Autowired
    SetupService SetupServiceImpl;
    @PostMapping("/bacAccaddAll")
    @ResponseBody
    @ApiOperation(value = "账号导入")
    public JsonResult bacAccaddAll(@RequestBody List<Account> accounts) {
        try{
        List<Account> accoun =new ArrayList<>();
        System.out.println("大姨大姨大姨");
        for (Account account1 : accounts) {
            System.out.println("22222:"+account1.toString());
            Account account = new Account();
            account.setAccountName(account1.getAccountName());//账号名称
            account.setAccountpwd(account1.getAccountpwd());//账号密码
            account.setAccountType(account1.getAccountType());//账号类型
            account.setInvcount(0);//邀请码数量
            account.setExpireDays(account1.getExpireDays());//天数
            account.setMailboxName(account1.getMailboxName());//邮箱名称
            account.setMailboxPwd(account1.getMailboxPwd());//邮箱密码
            account.setAuthorization(account1.getAuthorization());//邮箱授权码
            account.setHost(account1.getHost());//邮箱服务器地址
            account.setRemark(account1.getRemark());//备注
            //account.setStandbyid(account1.getStandbyid);//备用账号id
            accoun.add(account);
        }
        int insertaccounts = AccountServiceImpl.insertaccountsAll(accoun);
        if(insertaccounts==0){
            return JsonResult.ERROR("导入失败");
        }
        return JsonResult.OK("导入成功");
    }catch (Exception e){
        return JsonResult.ERROR("发现错误："+e.getMessage());
    }
    }

    @PostMapping("/bacAccadd")
    @ResponseBody
    @ApiOperation(value = "单个账号添加")
    public JsonResult bacAccadd( String AccountName,
                                 String Accountpwd,
                                 String AccountType,
                                 Integer Invcount,
                                 Integer ExpireDays,
                                 String MailboxName,
                                 String MailboxPwd,
                                 String Authorization,
                                 String Host,
                                 String Remark) {
        try{
        Account account = new Account();
        account.setAccountName(AccountName);//账号名称
        account.setAccountpwd(Accountpwd);//账号密码
        account.setAccountType(AccountType);//账号类型
        account.setInvcount(0);//邀请码数量
        account.setExpireDays(ExpireDays);//天数
        account.setMailboxName(MailboxName);//邮箱名称
        account.setMailboxPwd(MailboxPwd);//邮箱密码
        account.setAuthorization(Authorization);//邮箱授权码
        account.setHost(Host);//邮箱服务器地址
        account.setRemark(Remark);//备注
        //account.setStandbyid(null);//备用账号id
        int insertaccounts = AccountServiceImpl.insertaccounts(account);
        if(insertaccounts==0){
            return JsonResult.ERROR("导入失败");
        }
        return JsonResult.OK("导入成功");
    }catch (Exception e){
        return JsonResult.ERROR("发现错误："+e.getMessage());
    }
    }


    @PostMapping("/bacAccaddselAll")
    @ResponseBody
    @ApiOperation(value = "账号显示")
    public JsonResult bacAccaddselAll(@RequestParam(value="pageSize",defaultValue="5")Integer pageSize,
                                   @RequestParam(value="pageNum",defaultValue="1")Integer pageNum,
                                   String name) {
        Map<String,Object> map = new HashMap<>();
        name = "%"+name+"%";
        map.put("name",name);
        PageInfo<Map<String, Object>> mapPageInfo=null;
        mapPageInfo = AccountServiceImpl.selaccountAll(pageNum, pageSize, map);
        return JsonResult.OK(mapPageInfo);
    }

    @PostMapping("/bacAccaddupdate")
    @ResponseBody
    @ApiOperation(value = "账号修改")
    public JsonResult bacAccaddupdate(Integer Accountid,
                                      String AccountName,
                                      String Accountpwd,
                                      String AccountType,
                                      Integer Invcount,
                                      Integer ExpireDays,
                                      String MailboxName,
                                      String MailboxPwd,
                                      String Authorization,
                                      String Host,
                                      String Remark,
                                      Integer Standbyid
                                      ) {
        try{
        Account account = new Account();
        account.setAccountid(Accountid);//账号id
        account.setAccountName(AccountName);//账号名称
        account.setAccountpwd(Accountpwd);//账号密码
        account.setAccountType(AccountType);//账号类型
        account.setInvcount(Invcount);//邀请码数量
        account.setExpireDays(ExpireDays);//天数
        account.setMailboxName(MailboxName);//邮箱名称
        account.setMailboxPwd(MailboxPwd);//邮箱密码
        account.setAuthorization(Authorization);//邮箱授权码
        account.setHost(Host);//邮箱服务器地址
        account.setRemark(Remark);//备注
        account.setStandbyid(Standbyid);//备用账号id
        if(Standbyid!=null){
            StanAccountServiceImpl.updateaccountStart(Standbyid,1);
        }
        //修改
        int updateaccount = AccountServiceImpl.updateaccount(account);
        if(updateaccount==0){
            return JsonResult.ERROR("修改失败");
        }
        return JsonResult.OK("修改成功");
        }catch (Exception e){
            return JsonResult.ERROR("发现错误："+e.getMessage());
        }
    }

    @PostMapping("/AccBacdeleteAll")
    @ResponseBody
    @ApiOperation(value = "账号表根据id批量删除")
    public JsonResult AccBacdeleteAll(String Accountid) {
        try {
            String buy= Accountid.substring(1,Accountid.length()-1);
            List<Integer> list = new ArrayList<Integer>();
            String[] str = buy.split(",");
            for (int i = 0; i < str.length; i++) {
                int i1 = Integer.parseInt(str[i]);
                list.add(i1);
            }
            Integer i = AccountServiceImpl.delAccBccAll(list);
            return JsonResult.OK("删除成功");
        }catch (Exception e){
            return JsonResult.ERROR("删除失败");
        }
    }

    @PostMapping("/AccBacdelete")
    @ResponseBody
    @ApiOperation(value = "账号表根据id删除")
    public JsonResult AccBacdelete(Integer Accountid) {
        try {
            Integer i = AccountServiceImpl.delAccBccid(Accountid);
            return JsonResult.OK("删除成功");
        }catch (Exception e){
            return JsonResult.ERROR("删除失败");
        }
    }

    @PostMapping("/BacInvcreate")
    @ResponseBody
    @ApiOperation(value = "单个邀请码生成")
    public JsonResult BacInvcreate(Integer Accountid,Integer InvitationDays,Double BuyMoney,Integer count) {
        try{
        List<Invitation> list = new ArrayList<>();
        String AccountType = AccountServiceImpl.selType(Accountid);//查类型
            Setup setups = SetupServiceImpl.setsetupAll();
            int logNum=0;
            try{
                logNum=Integer.parseInt(setups.getReserved1());
            }catch (NumberFormatException e){}
        for (Integer i = 0; i < count; i++) {
            Account account = AccountServiceImpl.selAcc(Accountid);
            String s = UuidUtil.ToPinyin(AccountType);//类型中文变拼音
            String mail=account.getMailboxName();
            String[] code = mail.split("@");
            String mailName=code[0];
            Date date = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmm");
            String format = formatter.format(date);
            String InvitationCode = UuidUtil.getUUID(InvitationDays.toString(),s,account.getAccountName(),mailName,format);//生成邀请码
            Invitation invitation = new Invitation();
            invitation.setInvitationCode(InvitationCode);//邀请码
            invitation.setInvitationDays(InvitationDays);//邀请码天数
            invitation.setBuyMoney(BuyMoney);//购买金额
            invitation.setVoucher("");//购买凭证
            invitation.setState(3);//状态 生成
            invitation.setLogNum(logNum);//登录次数
            invitation.setResidue(InvitationDays);//到期天数
            invitation.setAccountid(Accountid);//账号id
            invitation.setAccountType(AccountType);//类型
            list.add(invitation);
        }
        int i = InvitationServiceImpl.insertInvAll(list);
        if(i==0){
            return JsonResult.ERROR("生成失败");
        }
        int i1 = AccountServiceImpl.updateInvCount(count, Accountid);
        return JsonResult.OK("生成成功");
    }catch (Exception e){
        return JsonResult.ERROR("发现错误："+e.getMessage());
    }
    }

    @PostMapping("/BacInvcreateAll")
    @ResponseBody
    @ApiOperation(value = "多个邀请码生成")
    public JsonResult BacInvcreateAll(String Accountid,Integer InvitationDays,Double BuyMoney,Integer count) {
        try {
            List<Invitation> list = new ArrayList<>();
            String buy = Accountid.substring(1, Accountid.length() - 1);
            List<Integer> list1 = new ArrayList<Integer>();
            String[] str = buy.split(",");
            for (int i = 0; i < str.length; i++) {
                int i1 = Integer.parseInt(str[i]);
                list1.add(i1);
            }
            Setup setups = SetupServiceImpl.setsetupAll();
            int logNum=0;
            try{
                logNum=Integer.parseInt(setups.getReserved1());
            }catch (NumberFormatException e){}
            for (Integer integer : list1) {
                String AccountType = AccountServiceImpl.selType(integer);//查类型
                Account account = AccountServiceImpl.selAcc(integer);
                for (Integer i = 0; i < count; i++) {
                    String s = UuidUtil.ToPinyin(AccountType);//类型中文变拼音
                    String mail = account.getMailboxName();
                    String[] code = mail.split("@");
                    String mailName = code[0];
                    Date date = new Date();
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmm");
                    String format = formatter.format(date);
                    String InvitationCode = UuidUtil.getUUID(InvitationDays.toString(), s, account.getAccountName(), mailName, format);//生成邀请码
                    Invitation invitation = new Invitation();
                    invitation.setInvitationCode(InvitationCode);//邀请码
                    invitation.setInvitationDays(InvitationDays);//邀请码天数
                    invitation.setBuyMoney(BuyMoney);//购买金额
                    invitation.setVoucher("");//购买凭证
                    invitation.setState(3);//状态 生成
                    invitation.setLogNum(logNum);//登录次数
                    invitation.setResidue(InvitationDays);//到期天数
                    invitation.setAccountid(integer);//账号id
                    invitation.setAccountType(AccountType);//类型
                    list.add(invitation);
                }
            }
            int i = InvitationServiceImpl.insertInvAll(list);
            if (i == 0) {
                return JsonResult.ERROR("生成失败");
            }
            //循环在账号中添加邀请码数量
            for (Integer integer : list1) {
                int i1 = AccountServiceImpl.updateInvCount(count, integer);
            }

            return JsonResult.OK("生成成功");
        }catch (Exception e){
           return JsonResult.ERROR("发现错误："+e.getMessage());
        }
    }



    @PostMapping("/setupup")
    @ResponseBody
    @ApiOperation(value = "设置表修改")
    public JsonResult setupup(Integer feedback,Integer logmin,String reserved1,String reserved2,String reserved3,String reserved4) {
        Setup setups = SetupServiceImpl.setsetupAll();
        int logNum=0;
        try{
            logNum=Integer.parseInt(reserved1);
        }catch (NumberFormatException e){}
        if(!setups.getReserved1().equalsIgnoreCase(reserved1)){
            int uplog = InvitationServiceImpl.uplog(logNum);
        }
        Setup setup = new Setup();
        setup.setFeedback(feedback);
        setup.setLogmin(logmin);
        setup.setReserved1(reserved1);
        setup.setReserved2(reserved2);
        setup.setReserved3(reserved3);
        setup.setReserved4(reserved4);
        int upsetup = SetupServiceImpl.upsetup(setup);
        if(upsetup!=1){
            return JsonResult.ERROR("修改错误");
        }
        return JsonResult.OK();
    }

    @PostMapping("/setupAll")
    @ResponseBody
    @ApiOperation(value = "设置表查询")
    public JsonResult setupAll() {
        Setup setups = SetupServiceImpl.setsetupAll();
            if(setups==null){
                return JsonResult.ERROR("错误");
            }
        return JsonResult.OK(setups);
    }
}
